package de.openlaboratory.elib.core;

import javax.ejb.Lock;
import javax.ejb.Singleton;

import de.openlaboratory.elib.controller.ElibService;
import de.openlaboratory.elib.controller.library.AuthorFacade;
import de.openlaboratory.elib.controller.library.LibraryFacade;
import de.openlaboratory.elib.controller.library.PublicationFacade;
import de.openlaboratory.elib.model.library.Author;
import de.openlaboratory.elib.model.library.Library;
import de.openlaboratory.elib.model.library.Publication;
import de.openlaboratory.elib.utilities.Operation;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static javax.ejb.LockType.READ;
import static javax.ejb.LockType.WRITE;

@Singleton
@Lock(READ)
public class ComponentRegistry
{
	private final Map<Class, Object> components = new HashMap<Class, Object>();

	public <T> T getComponent(Class<T> type)
	{
		return (T) components.get(type);
	}

	public Collection<?> getComponents()
	{
		return new ArrayList(components.values());
	}

	@Lock(WRITE)
	public <T> T setComponent(Class<T> type, T value)
	{
		return (T) components.put(type, value);
	}

	@Lock(WRITE)
	public <T> T removeComponent(Class<T> type)
	{
		return (T) components.remove(type);
	}

	public static ElibService lookupService(String action, String command)
	{
		return new PublicationFacade();
	}

	public static <T> ElibService lookupService(Class<T> type, String command)
	{
		if (type.getName().equals(Library.class.getName()))
		{
			return new LibraryFacade();
		}
		else if(type.getName().equals(Publication.class.getName()))
		{
			return new PublicationFacade();
		}
		return null;
	}
	

	public static <T> ElibService lookupService(Class<T> type, Operation op)
	{
		if (type.getName().equals(Library.class.getName()))
		{
			return new LibraryFacade();
		}
		else if(type.getName().equals(Publication.class.getName()))
		{
			return new PublicationFacade();
		}
		else if(type.getName().equals(Author.class.getName()))
		{
			return new AuthorFacade();
		}
		return null;
	}
}